package com.etc.controller;


import com.etc.entity.*;
import com.etc.service.LiveService;
import com.etc.util.ZegoServerAssistant;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


@Controller
@RequestMapping("LiveController")
public class LiveController{
    
    @Autowired
    private LiveService liveService;

    /**
     * 跳转到直播页
     * @return
     */
    @RequestMapping("classify")
    public ModelAndView classify(@RequestParam(value = "typeName",defaultValue = "") String typeName
            ,@RequestParam(value = "typeId",defaultValue = "")String typeId){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("typeName",typeName);
        modelAndView.addObject("typeId",typeId);
        modelAndView.setViewName("live/classify");
        
        return modelAndView;
    }
    /**
     * 跳转后台直播间管理界面
     * @return
     */
    @RequestMapping("BackLive")
    public String live(){
        return "backstage/live/liveAll";
    }
    /**
     * 跳转后台分类界面
     * @return
     */
    @RequestMapping("BackType")
    public String type(){
        return "backstage/type/typeAll";
    }
    /**
     * 跳转后台礼物管理界面
     * @return
     */
    @RequestMapping("BackGift")
    public String gift(){
        return "backstage/gift/giftAll";
    }

    /**
     * 跳转后台礼物记录管理界面
     * @return
     */
    @RequestMapping("BackGiftRecord")
    public String giftRecord(){
        return "backstage/gift/giftRecordAll";
    }

    /**
     * 新增分类
     * @return
     */
    @RequestMapping("addType")
    @ResponseBody
    public boolean addType(@RequestParam("typeName") String typeName){
        Type type = new Type();
        type.setTypeName(typeName);
        return liveService.addType(type);
    }
    /**
     * 修改分类
     * @return
     */
    @RequestMapping("setType")
    @ResponseBody
    public boolean setType(Type type){
        return liveService.updateType(type);
    }

    /**
     * 根据id查询分类
     * @param typeId
     * @return
     */
    @RequestMapping("getTypeByid")
    @ResponseBody
    public boolean getTypeByid(@RequestParam("typeId") String typeId){
        return liveService.queryTypeByTypeId(typeId);
    }

    /**
     * 删除分类
     * @param typeId
     * @return
     */
    @RequestMapping("delType")
    @ResponseBody
    public boolean delType(@RequestParam("typeId") String typeId){
        return liveService.deleteType(typeId);
    }
    
    /**
     * 礼物分页
     * @return
     */
    @RequestMapping("getGiftPage")
    @ResponseBody
    public PageInfo<Gift> getGiftPage(
            @RequestParam(value = "giftName",defaultValue = "") String giftName
            ,@RequestParam(value = "pageNo",defaultValue = "1")int pageNo
            ,@RequestParam(value = "pageSize",defaultValue = "5")int pageSize){
        PageInfo<Gift> pageInfo = liveService.queryGift(giftName, pageNo, pageSize);
        return pageInfo;
    }

    /**
     * 新增礼物
     * @return
     */
    @RequestMapping("addGift")
    @ResponseBody
    public boolean addGift(@RequestParam("giftName") String giftName,
                           @RequestParam("giftPrice") String giftPricee,
                           @RequestParam("giftImg") String giftImg,
                           @RequestParam("giftGif") String giftGif){
        BigDecimal giftPriceebig = new BigDecimal(giftPricee);
        return liveService.addGift(new Gift(giftName,giftImg,giftGif,giftPriceebig));
    }

    /**
     * 修改礼物
     * @return
     */
    @RequestMapping("setGift")
    @ResponseBody
    public boolean setGift(@RequestParam("giftName") String giftName,
                           @RequestParam("giftPrice") String giftPricee,
                           @RequestParam("giftImg") String giftImg,
                           @RequestParam("giftGif") String giftGif,
                           @RequestParam("giftId") String giftId){
        BigDecimal bigDecimal = new BigDecimal(giftPricee);
        return liveService.setGift(new Gift(giftId,giftName,giftImg,giftGif,bigDecimal));
    }

    @RequestMapping("delGift")
    @ResponseBody
    public boolean delGift(@RequestParam("giftId") String giftId){
        return liveService.deleteGift(giftId);
    }

    /**
     * 房间分页
     * @return
     */
    @RequestMapping("getRoomPage")
    @ResponseBody
    public PageInfo<Room> getRoomPage(
            @RequestParam(value = "anchor",defaultValue = "") String anchor
            ,@RequestParam(value = "roomName",defaultValue = "") String roomName
            ,@RequestParam(value = "pageNo",defaultValue = "1")int pageNo
            ,@RequestParam(value = "pageSize",defaultValue = "5")int pageSize){
        System.out.println(anchor+","+roomName);
        PageInfo<Room> pageInfo = liveService.queryRoom(anchor, roomName, pageNo, pageSize);
        return pageInfo;
    }

    /**
     * 新增房间
     * @return
     */
    @RequestMapping("addRoom")
    @ResponseBody
    public boolean addRoom(@RequestParam("roomName") String roomName,
                           @RequestParam("typeId") String typeId,
                           @RequestParam("userId") String userId,
                           @RequestParam("roomImg") String roomImg,
                           @RequestParam("roomState") int roomState){
        return liveService.addRoom(new Room(new User(userId),roomName,0,new Type(typeId),roomImg,roomState));
    }

    /**
     * 开播注册房间
     * @return
     */
    @RequestMapping("kbRoom")
    @ResponseBody
    public boolean kbRoom(@RequestParam(value = "roomName",defaultValue = "默认标题") String roomName,
                           @RequestParam(value = "typeId",defaultValue = "无") String typeId,
                           @RequestParam(value = "userId") String userId,
                           @RequestParam(value = "roomImg") String roomImg,
                           @RequestParam(value = "roomState",defaultValue = "1") int roomState){
        return liveService.addRoom(new Room(new User(userId),roomName,0,new Type(typeId),roomImg,roomState));
    }
    /**
     * 修改房间
     * @return
     */
    @RequestMapping("setRoom")
    @ResponseBody
    public boolean setRoom(@RequestParam("roomName") String roomName,
                           @RequestParam("typeId") String typeId,
                           @RequestParam("userId") String userId,
                           @RequestParam("roomImg") String roomImg,
                           @RequestParam("roomState") int roomState,
                           @RequestParam("roomId") String roomId){
        return liveService.updateRoom(new Room(roomId,new User(userId),roomName,0,new Type(typeId),roomImg,roomState));
    }
    
    /**
     * 跳转主播直播界面
     * @param session
     * @param roomId
     * @return
     */
    @RequestMapping("live/{roomId}")
    public String live(HttpSession session, @PathVariable String roomId){
        session.setAttribute("roomId",roomId);
        return "live/live";
    }

    /**
     * 跳转用户播放界面
     * @param session
     * @param roomId
     * @return
     */
    @RequestMapping("livePage/{roomId}")
    public String livePage(HttpSession session,@PathVariable String roomId){
        session.setAttribute("roomId",roomId);
        return "live/livePage";
    }

    /**
     * 获取直播房间令牌(接口)
     * @param roomId
     * @param userId
     * @return
     */
    @RequestMapping("Token")
    @ResponseBody
    public ZegoServerAssistant.TokenInfo getToken(@RequestParam(value = "roomId")String roomId
            ,@RequestParam(value = "userId") String userId){
        long appId = 3982261004L;
        String secret = "abc79eb8ba8389d41208b008525f5bdf";
        int effectiveTimeInSeconds = 86400;
        ZegoServerAssistant.Privileges privileges = new ZegoServerAssistant.Privileges();
        privileges.canLoginRoom = true;
        return ZegoServerAssistant.generateToken(appId, roomId, userId, privileges, secret, effectiveTimeInSeconds);
    }

    /**
     * 设置直播房间名
     * @param roomId
     * @param roomName
     * @return
     */
    @RequestMapping(value = "setRoomName/{roomId}/{roomName}",method = RequestMethod.PUT)
    @ResponseBody
    public boolean setRoomName(@PathVariable("roomId") String roomId, @PathVariable("roomName") String roomName){
        Room room = new Room();
        room.setRoomName(roomName);
        room.setRoomId(roomId);
        return liveService.updateRoom(room);
    }
    
    /**
     * 设置直播间状态
     * @param roomId
     * @return
     */
    @RequestMapping(value = "setRoomState/{roomId}/{state}",method = RequestMethod.PUT)
    @ResponseBody
    public boolean setRoomState(@PathVariable("roomId") String roomId, @PathVariable("state") String state){
        Room room = new Room();
        room.setRoomState(Integer.parseInt(state));
        room.setRoomId(roomId);
        return liveService.updateRoom(room);
    }

    /**
     * 删除直播间
     * @param roomId
     * @return
     */
    @RequestMapping(value = "delRoom")
    @ResponseBody
    public boolean delRoom(@RequestParam("roomId") String roomId){
        return liveService.deleteRoom(roomId);
    }

    /**
     * 获取直播间信息
     * @param roomId
     * @return
     */
    @GetMapping("getRoom/{roomId}")
    @ResponseBody
    public Room getRoom(@PathVariable("roomId") String roomId){
        return liveService.queryRoomById(roomId);
    }

    /**
     * 获取礼物列表
     * @return
     */
    @RequestMapping("getGiftList")
    @ResponseBody
    public List<Gift> getGiftList(){
        List<Gift> gifts = liveService.queryGiftList();
        return gifts;
    }

    /**
     * 送礼物并返回记录
     * @param giftId
     * @param userId
     * @return
     */
    @RequestMapping("getGiftById")
    @ResponseBody
    public GiftRecord getGiftById(@RequestParam("giftId") String giftId,@RequestParam("userId") String userId){
        return liveService.getRecord(giftId,userId);
    }

    /**
     * 分类分页
     * @param typeName
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("getType")
    @ResponseBody
    public PageInfo<Type> getType(@RequestParam(value = "typeName",defaultValue = "") String typeName,
                                  @RequestParam(value = "pageNo",defaultValue = "1") int pageNo,
                                  @RequestParam(value = "pageSize",defaultValue = "5") int pageSize){
        return liveService.queryType(typeName,pageNo,pageSize);
    }

    @RequestMapping("getUser")
    @ResponseBody
    public PageInfo<User> getUser(@RequestParam(value = "userName",defaultValue = "") String userName,
                                  @RequestParam(value = "pageNo",defaultValue = "1") int pageNo,
                                  @RequestParam(value = "pageSize",defaultValue = "5") int pageSize){
        return liveService.queryUser(userName,pageNo,pageSize);
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request) {
        Map<String, String> modelMap = new HashMap<>();
       // Gson gson = new Gson();
        String fileName = "";
        if (!file.isEmpty()) {
            String storePath = "E://video";
            Random r = new Random();
            fileName = file.getOriginalFilename();
            //String[] split = fileName.split(".jpg");
            fileName = r.nextInt(1000)+fileName;
            //fileName = fileName + ".jpg";
            File filePath = new File(storePath, fileName);
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();// 如果目录不存在，则创建目录
            }
            try {
                file.transferTo(new File(storePath + File.separator + fileName));// 把文件写入目标文件地址

            } catch (Exception e) {
                e.printStackTrace();
                modelMap.put("error","上传失败!");
                //String json = gson.toJson(modelMap);
                return modelMap;
            }
        } else {
            fileName = "上传失败!";
        }
        modelMap.put("img",fileName);
        //String json = gson.toJson(modelMap);
        return modelMap;

    }

    @RequestMapping("getGiftRecordPage")
    @ResponseBody
    public PageInfo<GiftRecord> getGiftRecordPage(@RequestParam(value = "giftRecordId",defaultValue = "") String giftRecordId,
                                            @RequestParam(value = "giftName",defaultValue = "") String giftName,
                                            @RequestParam(value = "pageNo",defaultValue = "1") int pageNo,
                                            @RequestParam(value = "pageSize",defaultValue = "5") int pageSize){
        return liveService.getGiftRecordList(giftRecordId,giftName,pageNo,pageSize);
    }

    @RequestMapping("getRoomListToConcernNum")
    @ResponseBody
    public PageInfo<Room> getRoomListToConcernNum(@RequestParam(value = "pageNo",defaultValue = "1") int pageNo,
                                                  @RequestParam(value = "pageSize",defaultValue = "6") int pageSize){
        return liveService.queryRoomListToConcernNum(pageNo,pageSize);
    }

    @RequestMapping("getRoomToUserId")
    @ResponseBody
    public Room getRoomToUserId(@RequestParam(value = "userId") String userId){
        Room room = liveService.queryRoomToUserId(userId);
        if (room==null){
            return new Room();
        }
        return room;
    }
}
